package com.example.gybicycle.controller.common;

import  com.alibaba.fastjson.JSON;
import  com.alibaba.fastjson.JSONObject;
import com.example.gybicycle.common.entity.Result;
import com.example.gybicycle.common.enums.NumType;
import com.example.gybicycle.common.util.DataUtil;
import com.example.gybicycle.common.util.NumberUtil;
import com.example.gybicycle.common.util.TreeUtil;
import com.example.gybicycle.common.wxPay.CallBackBody;
import com.example.gybicycle.common.wxPay.WechatPayExternalService;
import com.example.gybicycle.dao.*;
import com.example.gybicycle.entity.*;
import com.example.gybicycle.service.FileService;
import com.example.gybicycle.service.MemberPayService;
import com.example.gybicycle.service.PayService;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.refund.model.Refund;
import com.wechat.pay.java.service.refund.model.RefundNotification;
import com.wechat.pay.java.service.refund.model.Status;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import com.wechat.pay.java.service.payments.model.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.*;

@RestController
@Tag(name = "回调")
public class TXLockController {
    @Autowired
    private SysRoleDao roleDao;
    @Autowired
    private SysMenuDao menuDao;
    @Autowired
    private LockDao lockDao;
    @Autowired
    private BikeDao bikeDao;
    @Autowired
    private BikePointDao pointDao;
    @Autowired
    private SysDictDao dictDao;
    @Autowired
    private FileService fileService;
    @Autowired
    private WechatPayExternalService wxpayService;
    @Autowired
    private PayService payService;
    @Autowired
    private MemberPayService memberPayService;

    @PostMapping("/lock/callback")
    @Operation(summary = "获取锁订阅信息")
    public Result lock(@RequestBody String data) {

        JSONObject object = JSON.parseObject(data);
        if (object.get("payload") == null) {
            System.out.println("非开关锁记录");
        } else {
            String date = DataUtil.toString(new Date(), "yyyy-MM-dd HH:mm:ss");
            fileService.saveLockInfo(date + "-lock:\n " + data);
            JSONObject object1 = object.getJSONObject("payload");
            Integer state = object1.getInteger("state");
//            主锁编码
            String mainId = object1.getString("NO");
            String SN = object1.getString("SN");
            if (mainId == null || SN == null || state == null)
                return Result.fail("获取失败");
            String cid = SN.substring(1, 4);
            //子锁编码
            int number = Integer.parseInt(cid);
//            插销ID
            String latchNo = SN.substring(4);
            String lockId = "LOCK" + mainId + "D" + cid;
            if (state == 0) {
//                开锁
//                锁ID
                Lock lock = new Lock();
                lock.setId(lockId);
                lock.setState(1);
                lockDao.update(lock);
                Bike bike = new Bike();
                bike.setLatchNo(latchNo);
                bike.setBikeState(1);
                bikeDao.updateByLatNo(bike);
            } else if (state == 1) {
//                关锁
                Lock lock = new Lock();
                lock.setId(lockId);
                lock.setState(2);
                lockDao.update(lock);
                Bike bike = new Bike();
                bike.setLatchNo(latchNo);
                bike.setLockId(lockId);
                bike.setBikeState(0);
                bikeDao.updateByLatNo(bike);
            }
        }
        return Result.success("");
    }

    @PostMapping("/pay/callback")
    @Operation(summary = "获取支付信息")
    public Result pay(HttpServletRequest request) {
        String date = DataUtil.toString(new Date(), "yyyy-MM-dd HH:mm:ss");
//        fileService.saveFailPayInfo(date + "-pay:\n " + data);
        CallBackBody backBody = new CallBackBody();
        backBody.setSerial(request.getHeader("Wechatpay-Serial"));
        backBody.setNonce(request.getHeader("Wechatpay-Nonce"));
        backBody.setTimestamp(request.getHeader("Wechatpay-Timestamp"));
        backBody.setSignature(request.getHeader("Wechatpay-Signature"));
        backBody.setSignatureType(request.getHeader("Wechatpay-Signature-Type"));
        try {
            String line;
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            backBody.setBody(sb.toString());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Transaction transaction = wxpayService.payCallBack(backBody, Transaction.class);
        System.out.println("-----------------支付回调-------------------------");
        System.out.println(transaction);
        payService.wxpay(transaction);
        try {
            return Result.success("success");
        } catch (Exception e) {
            return Result.fail("error");
        }

    }

    @PostMapping("/pay/callbackLocal")
    @Operation(summary = "获取支付信息-本地")
    public Result payLocal(@RequestBody String data) {
        CallBackBody backBody = new CallBackBody();
        backBody.setSerial("3AD32CA89A2A2F7A8228988AE93E06B5158B5DFE");
        backBody.setNonce("4xCynMiP3okeHsnul6IUmHNdh5lR9XOL");
        backBody.setTimestamp("1721300330");
        backBody.setSignature("TaNMopzlMtOiCbXJbKvClOUXCBI+cRd4qjLjn7nvqQJctcruR6/ZXYOkVUDoJDOu6kBHcXOoI/VJvcoPWCIA3jwf0sWMws2ZkqlgkxgfYuFMWKQfPlZflxgfSFBpX6NUTEs7DnXNUdkdt1U+GDRqhF2DqIslcYUp31lo1gkSCi/BD/uQ+WaYZbkIxpOwlPd6g1ZoBWi319D8Mf52F1VjNBhFeOwKJnAOCgPFUlpfeDwrYA3dREHRSN9pIWJ42lda2+gT0eOF9iwnx7Pi0ZhzBIf+rpQuaARTsV3e2ugui/NEdwV0BQWNT/xahAYjDsFye3E/2gdDbTAYUgaDNptD5g==");
        backBody.setSignatureType("WECHATPAY2-SHA256-RSA2048");
        System.out.println(data);
        String obj = "{\"id\":\"e3672d9e-3dea-56d4-bd3e-912a29e4ccda\",\"create_time\":\"2024-07-18T18:58:50+08:00\",\"resource_type\":\"encrypt-resource\",\"event_type\":\"TRANSACTION.SUCCESS\",\"summary\":\"支付成功\",\"resource\":{\"original_type\":\"transaction\",\"algorithm\":\"AEAD_AES_256_GCM\",\"ciphertext\":\"fCw32mH4psuNPm6ORynzQzhsL2idCGy5QnrqQNT9GgCeQ2zaKIcjlT4kRfD81cfpLkwmWr1e62pXqkcoKjN+hmcFLRvDWD0/dbv4L2Dc00aNgatv+7SlUjm8hmAtOZZ2DCTfj9meGc6dbjZ56g/Rti/jHjTY4qdnNBdZC/JPjpI0gviqtAegpKawIGERJJD0a3Y2e63mfDynIfIoFnwIM1qtlYakldB0t9ZPLITd5TnajSKhjyUprKFqlQ815bh5nhD86ymqNcV/s2kz6W4pdRk09Cx81nju7jYKU5AKPxX6xSGQDSivT90LmNWFOYtc+VYnwOskskcsy+wyX9k/Gl7XbCBNoiAdTvDe0jpSaEAoIE6EtahXaiReVytgJ27I2DbV5H6d8D+/DuVNTg5LZkGaEDM1vjS1mioxXLUe5SPUwyKkCO6oskSuknoiuzOOGJJqKgsDRkYEt+5V4F6fbGznBzMwrQXFjkmWBMnNGxtkukCtDiinAxLGG2qRxRySjVxOyBvDerTnWxtx2UjHkPgOWvv/Ui6XUI2JlRumN2Q6fuj0D5eraEHKCRUSqrtp6zBcHnFHf0gBgDp9doXWRk4=\",\"associated_data\":\"transaction\",\"nonce\":\"uE82jntNBgsn\"}}";
        System.out.println(obj);
        backBody.setBody(obj);
//        obj:  {"id":"e3672d9e-3dea-
//        -bd3e-912a29e4ccda","create_time":"2024-07-18T18:58:50+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"支付成功","resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM","ciphertext":"fCw32mH4psuNPm6ORynzQzhsL2idCGy5QnrqQNT9GgCeQ2zaKIcjlT4kRfD81cfpLkwmWr1e62pXqkcoKjN+hmcFLRvDWD0/dbv4L2Dc00aNgatv+7SlUjm8hmAtOZZ2DCTfj9meGc6dbjZ56g/Rti/jHjTY4qdnNBdZC/JPjpI0gviqtAegpKawIGERJJD0a3Y2e63mfDynIfIoFnwIM1qtlYakldB0t9ZPLITd5TnajSKhjyUprKFqlQ815bh5nhD86ymqNcV/s2kz6W4pdRk09Cx81nju7jYKU5AKPxX6xSGQDSivT90LmNWFOYtc+VYnwOskskcsy+wyX9k/Gl7XbCBNoiAdTvDe0jpSaEAoIE6EtahXaiReVytgJ27I2DbV5H6d8D+/DuVNTg5LZkGaEDM1vjS1mioxXLUe5SPUwyKkCO6oskSuknoiuzOOGJJqKgsDRkYEt+5V4F6fbGznBzMwrQXFjkmWBMnNGxtkukCtDiinAxLGG2qRxRySjVxOyBvDerTnWxtx2UjHkPgOWvv/Ui6XUI2JlRumN2Q6fuj0D5eraEHKCRUSqrtp6zBcHnFHf0gBgDp9doXWRk4=","associated_data":"transaction","nonce":"uE82jntNBgsn"}}
        Transaction transaction = wxpayService.payCallBack(backBody, Transaction.class);
//        transaction=wxpayService.queryStatus(transaction.getOutTradeNo());

///        setAttach
        try {
            return Result.success("success");
        } catch (Exception e) {
            return Result.fail("error");
        }

    }

    @PostMapping("/pay/refund")
    @Operation(summary = "退款")
    public Result refund(@RequestBody String data) {
        String[] datas = data.split(",");
//        List<String> list= Arrays.asList("PAY202407190017","PAY202407190019","PAY202407190021","PAY202407190023","PAY202407190024","PAY202407190028","PAY202407190030","PAY202407190033","PAY202407190035","PAY202407190034","PAY202407190039","PAY202407190042", "PAY202407190045","PAY202407190047","PAY202407190049","PAY202407190051","PAY202407190052","PAY202407190053","PAY202407190054","PAY202407190056","PAY202407190058","PAY202407190061","PAY202407190063");
        for (String str : datas) {
//            String str="PAY2024071900"+i;
            MemberPay pay = new MemberPay();
            pay.setId(str);
            pay.setMoney(new BigDecimal(0.01));
            MemberPay pay2 = new MemberPay();
            pay2.setId(NumberUtil.getNum(NumType.PAY));
            System.out.println(pay2);

            try {
                Refund refund = wxpayService.refund(pay, pay2.getId());
                if (refund.getStatus().equals(Status.PROCESSING)) {
                    System.out.println(str + "退款成功");
                } else {
                    System.out.println(str + "失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(str + "失败");
            }

        }
        return Result.success("");

    }

    @PostMapping("/pay/refundcall")
    @Operation(summary = "退款")
    public Result refundcall(HttpServletRequest request) {
        var re = wxpayService.refundNotify(request);
        payService.wxRefund(re);
//       fileService.saveFailPayInfo("refund-info:  "+JSON.toJSONString(re));
        return Result.success("SUCCESS");
    }
    @PostMapping("/pay/refundtest")
    @Operation(summary = "退款回调测试")
    public Result refundcall(@RequestBody String data) {
        RefundNotification re=JSON.parseObject(data,RefundNotification.class);
        payService.wxRefund(re);
        return Result.success("SUCCESS");
    }
}
